package net.huadong.decoder.length;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * netty 粘包拆包 基于长度字段的消息帧解码器 客户端
 * ws
 */
public class NettyLengthTimeClient {

    /**
     * 开启监听
     *
     * @param port
     * @param host
     * @throws Exception
     */
    public void connect(int port, String host) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    //处理粘包拆包
                    socketChannel.pipeline().addLast(new FixedLengthFrameDecoder(16));

                    socketChannel.pipeline().addLast(new StringDecoder());

                    socketChannel.pipeline().addLast(new NettyLengthTimeClientHandler());
                }
            });
            ChannelFuture f = bootstrap.connect(host, port).sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();

        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        String ip = "127.0.0.1";
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        new NettyLengthTimeClient().connect(port, ip);
    }
}
